import { HttpError } from 'wasp/server'

export const submitQuery = async ({ question }, context) => {
  if (!context.user) { throw new HttpError(401) };

  return context.entities.Query.create({
    data: {
      question: question,
      answer: null,
      user: {
        connect: { id: context.user.id }
      }
    }
  });
}

export const provideAnswer = async ({ queryId, answerText }, context) => {
  if (!context.user) { throw new HttpError(401) };

  // Fetch the query to ensure it exists and user is authorized
  const query = await context.entities.Query.findUnique({
    where: { id: queryId },
    include: { user: true }
  });

  if (!query) { throw new HttpError(404, 'Query not found') };

  if (query.user.id !== context.user.id) { throw new HttpError(403, 'User not authorized to provide answer for this query') };

  // Update the query with the provided answer
  return context.entities.Query.update({
    where: { id: queryId },
    data: { answer: answerText }
  });
}
